<template>
  <el-dialog v-model="props.modelValue" style="margin-top:70px;" @close="hideModal(false, ruleFormRef)" append-to-body>
    <template #header>
      <div class="text-center font-bold text-[18px]">
        {{ props.pageType === 1 ? "编辑商品" : "新增商品" }}
      </div>
    </template>

    <el-form ref="ruleFormRef" :rules="rules" :model="form" class="text-black font-bold" size="large" label-width="auto">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入商品名称" />
          </el-form-item>
          <el-form-item label="封面图">
            <single-upload v-model="form.cover" v-model:hash="form.hash" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="IP" prop="pIp">
            <el-select class="w-full" v-model="form.pIp" placeholder="选择IP" size="large" clearable>
              <el-option v-for="item in (props.ip as any)" :key="item.value" :label="item.key" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select class="w-full" v-model="form.status" placeholder="选择状态" size="large" clearable>
              <el-option v-for="item in (props.status as any)" :key="item.value" :label="item.key" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="进货日期">
            <el-date-picker v-model="form.enterDate" type="datetime" placeholder="请选择时间" :default-time="new Date()" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="分类" prop="category">
            <el-select class="w-full" v-model="form.category" placeholder="选择分类" size="large" clearable>
              <el-option v-for="item in (props.category as any)" :key="item.value" :label="item.key"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="货源" prop="source">
            <el-select class="w-full" v-model="form.source" placeholder="选择货源" size="large" clearable>
              <el-option v-for="item in (props.source as any)" :key="item.value" :label="item.key" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="整盒价(￥)">
            <el-input-number v-model="form.boxPrice" :precision="2" :step="0.1" :max="1000" :min="0" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="库存(件/个)">
            <el-input-number v-model="form.stock" :max="10000" :min="0" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="进价(￥)">
            <el-input-number v-model="buyPrice" :precision="2" :step="0.1" :max="1000" :min="0" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="售价(￥)">
            <el-input-number v-model="form.sellPrice" :precision="2" :step="0.1" :max="1000" :min="0" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <!-- <el-col :span="12">
          <el-form-item label="指导价(￥)">
            <el-input-number v-model="form.guidePrice" :precision="2" :step="0.1" :max="1000" :min="0" />
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="12">
          <el-form-item label="折扣价(￥)">
            <el-input-number v-model="form.breakPrice" :precision="2" :step="0.1" :max="1000" :min="0" />
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="12" v-if="props.pageType === 0">
          <el-form-item :label="'邮费: '">
            <el-input-number v-model="form.postage" :precision="2" :max="10" :min="0" />
          </el-form-item>
        </el-col> -->
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button v-if="props.pageType == 0" size="large" type="success" @click="addProduct(ruleFormRef)">添加</el-button>
        <el-button v-if="props.pageType == 1" size="large" type="success"
          @click="updateProduct(ruleFormRef)">更新</el-button>
        <el-button size="large" type="primary" @click="hideModal(false, ruleFormRef)">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import ProductService from "@/api/ProductService";
import { FormInstance, UploadInstance, FormRules } from "element-plus";
import { Product } from "@/components/product/type"
import { KeyValueObj } from "@/common/GlobalType";
import Decimal from 'decimal.js';

type Props = {
  modelValue: boolean; // 组件 v-model 传值       默认属性名 modalValue
  category: KeyValueObj[];
  source: KeyValueObj[];
  ip: KeyValueObj[];
  status: KeyValueObj[];
  pageType: number;
  currentProduct: any | Product;
  refresh: Function;
};

const props = withDefaults(defineProps<Props>(), {
  category: [] as any,
  source: [] as any,
  status: [] as any,
});

const emit = defineEmits([
  "update:modelValue",
  "update:pageType",
  "update:currentProduct",
]);

const { proxy } = getCurrentInstance() as any;

const uploadRef = ref<UploadInstance>()
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules<typeof state.form>>({
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  pIp: [{ required: true, message: '请选择IP', trigger: 'blur' }],
  category: [{ required: true, message: '请选择种类', trigger: 'blur' }],
  source: [{ required: true, message: '请选择来源', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
})
const state = reactive({
  form: {
    image: [],
    cover: '',
    hash: '',
    pId: "",
    enterDate: new Date(),
    name: "",
    pIp: "",
    category: "",
    source: "",
    status: "",
    boxPrice: 0,
    stock: 0,
    buyPrice: 0,
    sellPrice: 0,
    guidePrice: 0,
    breakPrice: 0,
    postage: 0,
  },
});
const { form } = toRefs(state);

// 创建计算属性
const buyPrice = computed(() => {
  const { boxPrice, stock } = state.form
  if (boxPrice && stock) {
    return new Decimal(boxPrice).div(stock).toNumber()
  }
  return 0
});

// 监听计算属性的变化
watch(buyPrice, (newValue, oldValue) => {
  state.form.buyPrice = newValue
});

const hideModal = (bool: boolean, form: FormInstance | undefined) => {
  form?.resetFields()
  emit("update:modelValue", false);
  emit("update:pageType", 0);
  emit("update:currentProduct", {});
  bool && refresh();
};

const refresh = () => {
  props.refresh?.();
};

const addProduct = async (ruleFormRef: FormInstance | undefined) => {
  const result = await ruleFormRef?.validate().catch((e: any) => { });
  if (!result) return;

  const [err, res] = await ProductService.addProduct(state.form);
  if (err) {
    return proxy.$modal.msgSuccess(err);
  }
  proxy.$modal.msgSuccess("添加成功~");
  hideModal(true, ruleFormRef);
};

const updateProduct = async (ruleFormRef: FormInstance | undefined) => {
  const result = await ruleFormRef?.validate().catch((e: any) => { });
  if (!result) return;
  const {
    pId,
    cover,
    enterDate,
    name,
    pIp,
    buyPrice,
    sellPrice,
    guidePrice,
    breakPrice,
    category,
    source,
    status,
    stock,
    boxPrice,
  } = state.form;
  const params = {
    enterDate,
    name,
    cover,
    pIp,
    category,
    source,
    status,
    buyPrice,
    sellPrice,
    guidePrice,
    breakPrice,
    stock,
    boxPrice,
  };
  const [err, res] = await ProductService.updateProduct(pId, params);
  if (err) {
    return proxy.$modal.msgSuccess(err);
  }
  proxy.$modal.msgSuccess("更新成功~");
  hideModal(true, ruleFormRef);
}

const init = () => {
  if (props.pageType === 1) {
    const { buyPrice, sellPrice, guidePrice, breakPrice, boxPrice } = props.currentProduct;
    props.currentProduct.boxPrice = parseFloat(boxPrice);
    props.currentProduct.buyPrice = parseFloat(buyPrice);
    props.currentProduct.sellPrice = parseFloat(sellPrice);
    props.currentProduct.guidePrice = parseFloat(guidePrice);
    props.currentProduct.breakPrice = parseFloat(breakPrice);
    state.form = props.currentProduct;
  }
};

init();
</script>

<style lang="scss" scoped></style>
